const fs = require('fs');
const path = require('path');
const marked = require('marked');
const puppeteer = require('puppeteer');
const { cosmiconfigSync } = require('cosmiconfig');


// inquirer 能让用户输入的交互
// figlet 打印大型文字
// chalk 彩色字符

module.exports = async (mdFileName, opt) => {
  if (typeof mdFileName !== 'string') {
    throw new Error(`${mdFileName} Expected a string, got ${typeof mdFileName}`);
  }

  // resolve 会解决相对/绝对路径的问题
  const filePath = path.resolve(mdFileName); // 内部自动基于 process.pwd()

  if (!fs.existsSync(filePath)) {
    throw new Error(`文件不存在`);
    return;
  }

  const stat = fs.statSync(filePath);
  if (stat.isDirectory()) {
    throw new Error(`请提供文件路径而不是文件夹`);
    return;
  }
  if (!stat.isFile()) {
    throw new Error(`请提供一个文件路径`);
    return;
  }

  // 读取文件
  const contents = fs.readFileSync(filePath, 'utf-8');

  // 获取html结构
  const htmlContent = marked.parse(contents);

  // 读配置文件
  const explorer = cosmiconfig('md2png');
  const { config = {} } = explorer.search(process.pwd()) || {};
  console.log('config==>', config);

  const html = config.template.replace('${htmlContent}', htmlContent);

  // 生成图片
  const bw = await puppeteer.launch();
  const page = await bw.newPage();
  await page.setViewport({ width: ~~opt.width, height: 10 });
  await page.setContent(html);
  await page.screenshot({ path: opt.output, fullPage: true });
  await bw.close();
};
